package com.nand.library.base.base;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.TextView;

import com.nand.library.base.R;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

/**
 * Created by 孝杰 on 2019/12/8.
 */
public abstract class BaseFragment extends Fragment {

    private ViewStub emptyView;
    private View rootView;
    protected Context mContext;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_base, container, false);
        ((ViewGroup) getView(R.id.fl_content)).addView(getLayoutInflater().inflate(getLayoutId(), null));
        return rootView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    protected abstract int getLayoutId();

    protected abstract void initView(View view);

    public <T extends View> T getView(int id) {
        View view = rootView.findViewById(id);
        return (T) view;
    }


    //***************************错误页面或空页面方法*****************************
    /**
     * 展示错误页面或空页面
     * @param text
     * @param img
     */
    public void showEmptyOrErrorView(String text, int img) {
        if (emptyView == null) {
            emptyView = rootView.findViewById(R.id.vs_empty);
        }
        emptyView.setVisibility(View.VISIBLE);
        rootView.findViewById(R.id.iv_empty).setBackgroundResource(img);
        ((TextView) rootView.findViewById(R.id.tv_empty)).setText(text);
        rootView.findViewById(R.id.ll_empty).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onPageClick();
            }
        });
    }

    /**
     * 隐藏错误页面
     */
    protected void hideEmptyView() {
        if (emptyView != null) {
            emptyView.setVisibility(View.GONE);
        }
    }

    /**
     * 空页面被点击
     */
    protected void onPageClick() {

    }

    protected void showEmptyView() {
        showEmptyOrErrorView(getString(R.string.no_data), R.mipmap.bg_no_data);
    }


    protected void showErrorView() {
        showEmptyOrErrorView(getString(R.string.error_data), R.mipmap.bg_no_net);
    }
    //***************************错误页面或空页面方法*****************************
}
